package com.auxgroup.smarthome.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Qiuhua Lai
 * @email qhlai@gizwits.com
 */
public final class WebUtils {
    private WebUtils(){}

    private static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = getServletRequestAttributes();
        if (null == attributes) {
            return null;
        }
        return attributes.getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = getServletRequestAttributes();
        if (null == attributes) {
            return null;
        }
        return attributes.getResponse();
    }

    public static boolean setRequestAttribute(String name, Object data) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return false;
        }
        request.setAttribute(name, data);
        return true;
    }

    public static Object getRequestAttribute(String name) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }

        return request.getAttribute(name);
    }

    public static boolean setSessionAttribute(String name, Object data) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return false;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(name, data);
        return true;
    }

    public static Object getSessionAttribute(String name) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        HttpSession session = request.getSession(true);
        return session.getAttribute(name);
    }

}
